package rmi.server;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import rmi.Product;

public class Order {

    private String clientName;
    private int orderNr;
    private boolean isConfirmed;
    private List<OrderTuple> tupleList = new ArrayList<OrderTuple>();

    public Order() {
    }

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public int getOrderNr() {
        return orderNr;
    }

    public void setOrderNr(int orderNr) {
        this.orderNr = orderNr;
    }

    public boolean isConfirmed() {
        return isConfirmed;
    }

    public void setIsConfirmed(boolean value) {
        isConfirmed = value;
    }

    public List<OrderTuple> getTupleList() {
        return tupleList;
    }

    public int getProductIndex(Product p) {
        int index = -1;
        boolean found = false;
        for (int i = 0; i < tupleList.size() && !found; i++) {
            if (tupleList.get(i).getProduct().equals(p)) {
                index = i;
                found = true;
            }
        }
        return index;
    }
    
    public String getSummary() {
        String summary = null;
        summary = "Summary of your order: \n";
        for (OrderTuple ot : getTupleList()) {
            try {
                summary += ot.getAmount() + " \t" + ot.getProduct().getDescription() + "\n";
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
        }
        return summary;
    }

    public boolean addTuple(int someAmount, Product p) {
        boolean succes = false;
        if (!isConfirmed) {
            int index = getProductIndex(p);
            if (index != -1) {
                OrderTuple ot = tupleList.get(index);
                int amount = ot.getAmount();
                amount += someAmount;
                ot.setAmount(amount);
            } else {
                OrderTuple ot = new OrderTuple();
                ot.setProduct(p);
                ot.setAmount(someAmount);
                tupleList.add(ot);
            }
            succes = true;
        }
        return succes;
    }

    public class OrderTuple {

        private int amount;
        private Product product;

        public int getAmount() {
            return amount;
        }

        public void setAmount(int amount) {
            this.amount = amount;
        }

        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }
    }
}
